﻿using System;
using System.Reflection;

namespace SimpleBoard.Designer.Extensions
{
    public static class ObjectExtension
    {
        /// <summary>
        /// 通过反射获取指定名称的属性值
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="propertyName"></param>
        /// <returns></returns>
        /// <exception cref="InvalidOperationException"></exception>
        public static object? GetPropertyValue(this object obj, string propertyName)
        {
            if (obj is null) return null;
            var type = obj.GetType();
            if (type.GetProperty(propertyName) is not PropertyInfo propInfo) throw new InvalidOperationException("不存在的属性");
            return propInfo.GetValue(obj);
        }

        /// <summary>
        /// 通过反射设置属性值
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="propertyName"></param>
        /// <param name="value"></param>
        /// <exception cref="InvalidOperationException"></exception>
        public static void SetPropertyValue(this object obj, string propertyName, object value)
        {
            if (obj is null) return;
            var type = obj.GetType();
            if (type.GetProperty(propertyName) is not PropertyInfo propInfo) throw new InvalidOperationException("不存在的属性");
            propInfo.SetValue(obj, value);
        }
    }
}
